#include <stdio.h>
#include <string.h>
//以26度，自动风力，制冷模式开启空调
void GreeAircon_On(void) {
	IR_SendHead();
	IR_SendStringBits("10010000010100000000010000001010010");
	IR_SendCat();
	IR_SendStringBits("00000000000001000000000000001111");
	IR_SendLongCat();
	IR_SendHead();
	IR_SendStringBits("10010010010100000000010000001110010");
	IR_SendCat();
	IR_SendStringBits("00000000000000000000000000001011");
	IR_SendLongCat();
}
//关闭空调
void GreeAircon_Off(void) {
	IR_SendHead();
	IR_SendStringBits("10000010010100000000010000001010010");
	IR_SendCat();
	IR_SendStringBits("00000000000001000000000000001110");
	IR_SendLongCat();
	IR_SendHead();
	IR_SendStringBits("10000010010100000000010000001110010");
	IR_SendCat();
	IR_SendStringBits("00000000000000000000000000001010");
	IR_SendLongCat();
}
/*
* 校验码的計算方法： 前四个字节的前四位，翻转后相加，后三个字节的后四位，翻转后相加，所得结果对16取余，再翻转的四位二进制
*/
//以指定温度和风力(0为自动)，制冷模式 开启空调(或设置空调)
void GreeAircon_SetStatus(unsigned char temperature,unsigned char fanMode) {
  //按下一次按钮，遥控器将会向空调发送16个字节的数据，分为4条4字节的数据加连接码发出
	char code1[64] = {0}; //以字符串的形式分别保存4条4字节数据，虽然这是一种很浪费内存的表示方法，但是比较直观
	char code2[64] = {0}; //其中code1和code3是4字节+二进制010为结尾，这010似乎没什么意义，是厂商定好的
	char code3[64] = {0};
	char code4[64] = {0}; 
	char tempStr[5] = {0}; //一个临时的缓冲区，用来保存由数字转为2进制字符串的内容
	char checkSum1[5] = {0}; //用来保存第一个校验码
	char checkSum2[5] = {0}; //用来保存第二个校验码
  //用来保存风力 风力的表示方法：风力分为0-5,0为自动，1-5为等级
	char fanCode1[3] = {0}; //fanCode1:当风力小于3时，，保存风力二进制的倒序，当风力为3,4,5时，为固定值11
	char fanCode2[5] = {0}; //fanCode2保存的是0-5风力的二进制的倒序（低位在右）
	unsigned char checkSum = 0; //用来保存校验码的计算结果
	temperature -= 16; //实际温度为16到31度，对应发给空调的数据是0-15
	checkSum = 9 + temperature + 2 + 10; //计算第一个校验码
	if(temperature > 15)
		temperature = 15;
	if(fanMode > 5)
		fanMode = 5;
	Num2ReversedBinStr(temperature,tempStr,4); //此函数把数字以二进制倒序写入tempStr中
	Num2ReversedBinStr(checkSum%16,checkSum1,4);
	Num2ReversedBinStr(fanMode,fanCode2,4);
	if(fanMode < 3) {
		Num2ReversedBinStr(fanMode,fanCode1,2);
	} else {
		fanCode1[0] = '1';
		fanCode1[1] = '1';
		fanCode1[2] = 0;
	}
	checkSum = 9 + temperature + fanMode + 10; //计算第二个校验码
	Num2ReversedBinStr(checkSum%16,checkSum2,4);
	sprintf(code1,"1001%2s00%4s00000000010000001010010",fanCode1,tempStr); //生成要发给空调的指令数据
	sprintf(code2,"0000000000000100000000000000%4s",checkSum1);
	sprintf(code3,"1001%2s00%4s00000000010000001110010",fanCode1,tempStr);
	sprintf(code4,"00000000000000000000%-4s0000%4s",fanCode2,checkSum2); //%-4s表示左对齐，右侧多出部分用空格补充
	IR_SendHead();
	IR_SendStringBits(code1);
	IR_SendCat();
	IR_SendStringBits(code2);
	IR_SendLongCat();
	IR_SendHead();
	IR_SendStringBits(code3);
	IR_SendCat();
	IR_SendStringBits(code4);
	IR_SendLongCat();
}
//将给定数字转化为二进制表示的字符串，小端在后，写入p给定的内存中，长度为len，多余部分写为0
//如6将写为"011"
//如(num=6,len=5)将写为"01100"
void Num2ReversedBinStr(char num,char *p,char len) {
	while(num > 0) {
		*p = num % 2 | 0x30;
		p++;
		len--;
		num /= 2;
	}
	while(len > 0) {
		*p = '0';
		p++;
		len--;
	}
}